﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;

namespace D.UtilCore.Routes
{
    /// <summary>
    /// 全局路由前缀
    /// </summary>
    public class GlobalRoutePrefixConvention : IApplicationModelConvention
    {
        private readonly string _routePrefix;

        /// <summary>
        /// 全局路由前缀
        /// </summary>
        /// <param name="routePrefix">前缀</param>
        public GlobalRoutePrefixConvention(string routePrefix)
        {
            _routePrefix = routePrefix;
        }

        public void Apply(ApplicationModel application)
        {
            var centralPrefix = new AttributeRouteModel(new RouteAttribute(_routePrefix));
            foreach (var controller in application.Controllers)
            {
                var routeSelector = controller.Selectors.FirstOrDefault(x => x.AttributeRouteModel != null);

                if (routeSelector != null)
                {
                    routeSelector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(centralPrefix,
                        routeSelector.AttributeRouteModel);
                }
                else
                {
                    controller.Selectors.Add(new SelectorModel() { AttributeRouteModel = centralPrefix });
                }
            }
        }
    }
}
